<?php

namespace App\Http\Controllers\Api\Teacher;

use App\Models\Course;
use App\Models\Student;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use App\Http\Controllers\Controller;

class StudentController extends Controller
{
    /**
     * 学生列表（搜索参数放Body）
     * GET /api/teacher/students
     */
    public function index(Request $request)
    {
        // 从请求体获取搜索参数（支持JSON或表单数据）
        $name = $request->input('name');
        $phone = $request->input('phone');
        $status = $request->input('status');
        $page = $request->input('page', 1);
        $pageSize = $request->input('page_size', 10);

        $query = Student::query();

        // 搜索条件
        if (!empty($name)) {
            $query->where('name', 'like', "%{$name}%");
        }
        if (!empty($phone)) {
            $query->where('phone', 'like', "%{$phone}%");
        }
        if (isset($status)) { // 允许0值（禁用状态）
            $query->where('status', $status);
        }

        // 分页查询
        $students = $query->paginate($pageSize, ['*'], 'page', $page);
        $students->appends($request->except('page'));

        // 计算课程数量
        $studentItems = $students->items();
        foreach ($studentItems as $student) {
            $student->course_count = $student->courses()->count();
            
            // 为avatar字段添加域名前缀
            if ($student->avatar && !filter_var($student->avatar, FILTER_VALIDATE_URL)) {
                $baseUrl = config('app.base_url', config('app.url'));
                $student->avatar = rtrim($baseUrl, '/') . '/' . ltrim($student->avatar, '/');
            }
        }

        return $this->paginated($studentItems, $students);
    }

    /**
     * 新增学生（参数放Body）
     * POST /api/teacher/students
     */
    public function store(Request $request)
    {
        // 从请求体验证参数
        $request->validate([
            'username' => 'required|string',
            'password' => 'required|string',
            'name' => 'nullable|string',
            'phone' => 'nullable|string',
            'avatar' => 'nullable|string',
            'id_card' => 'nullable|string',
            'status' => 'boolean'
        ]);

        $avatarData = $request->input('avatar');
        $avatarPath = null;
        
        // 如果提供了base64格式的头像数据，则进行处理
        if ($avatarData && preg_match('/^data:image\/(\w+);base64,/', $avatarData, $matches)) {
            $extension = $matches[1];
            $imageData = substr($avatarData, strpos($avatarData, ',') + 1);
            $imageData = base64_decode($imageData);
            
            if ($imageData !== false) {
                // 生成唯一文件名
                $filename = 'avatar_' . Str::random(32) . '.' . $extension;
                $path = 'avatars/' . date('Y/m');
                
                // 保存文件到存储目录
                Storage::disk('public')->put($path . '/' . $filename, $imageData);
                
                // 获取文件路径
                $avatarPath = Storage::url($path . '/' . $filename);
            }
        } else if ($avatarData) {
            // 如果avatar不是base64数据但有内容，则直接使用该值（可能是URL）
            $avatarPath = $avatarData;
        }

        // return $this->success('123456', '创建成功', 500);

        $student = Student::create([
            'username' => $request->input('username'),
            'password' => Hash::make($request->input('password')),
            'name' => $request->input('name'),
            'phone' => $request->input('phone'),
            'avatar' => $avatarPath,
            'id_card' => $request->input('id_card'),
            'status' => $request->input('status', 1)
        ]);

        return $this->success($student, '创建成功', 200);
    }

    /**
     * 编辑学生（id放Body）
     * PUT /api/teacher/students
     */
    public function update(Request $request)
    {
        // 从请求体获取学生ID并验证
        $request->validate([
            'id' => 'required|integer|exists:students,id', // 必须包含id参数
            'username' => 'string|unique:students,username,' . $request->input('id'),
            'name' => 'nullable|string',
            'phone' => 'nullable|string',
            'avatar' => 'nullable|string',
            'id_card' => 'nullable|string',
            'status' => 'boolean'
        ]);

        $student = Student::findOrFail($request->input('id'));
        
        $data = $request->only(['name', 'phone', 'id_card', 'status']);
        if ($request->has('password')) {
            $data['password'] = Hash::make($request->input('password'));
        }
        if ($request->has('username')) {
            $data['username'] = $request->input('username');
        }
        
        $avatarData = $request->input('avatar');
        
        // 如果提供了base64格式的头像数据，则进行处理
        if ($avatarData && preg_match('/^data:image\/(\w+);base64,/', $avatarData, $matches)) {
            $extension = $matches[1];
            $imageData = substr($avatarData, strpos($avatarData, ',') + 1);
            $imageData = base64_decode($imageData);
            
            if ($imageData !== false) {
                // 生成唯一文件名
                $filename = 'avatar_' . Str::random(32) . '.' . $extension;
                $path = 'avatars/' . date('Y/m');
                
                // 保存文件到存储目录
                Storage::disk('public')->put($path . '/' . $filename, $imageData);
                
                // 获取文件路径
                $data['avatar'] = Storage::url($path . '/' . $filename);
            }
        } else if ($avatarData) {
            // 如果avatar不是base64数据但有内容，则直接使用该值（可能是URL）
            $data['avatar'] = $avatarData;
        }

        $student->update($data);
        return $this->success($student);
    }

    /**
     * 可绑定的课程列表
     * GET /api/teacher/students/available-courses
     */
    public function getAvailableCourses()
    {
        $courses = Course::where('teacher_id', auth('admin')->id())
                        ->where('status', 1)
                        ->get(['id', 'name', 'code']);

        return $this->success($courses);
    }
    
    /**
     * 获取学生已绑定的课程列表
     * GET /api/teacher/students/{id}/courses
     */
    public function getBoundCourses($id)
    {
        $student = Student::findOrFail($id);
        
        // 获取学生绑定的课程，包含开始时间和进度
        // 进度：0未学习，1学习中，2已完成
        $courses = $student->courses()
                          ->where('teacher_id', auth('admin')->id())
                          ->get(['courses.id', 'courses.name', 'courses.code'])
                          ->map(function($course) {
                              return [
                                  'id' => $course->id,
                                  'name' => $course->name,
                                  'code' => $course->code,
                                  'start_time' => $course->pivot->start_time,
                                  'progress' => $course->pivot->progress, // 进度：0未学习，1学习中，2已完成
                                  // 根据进度判断状态
                                  'status' => $course->pivot->progress == 2 ? 'completed' : 
                                             ($course->pivot->progress == 1 ? 'learning' : 'pending')
                              ];
                          });

        return $this->success($courses);
    }

    /**
     * 绑定课程（student_id和course_id放Body）
     * POST /api/teacher/students/bind-course
     */
    public function bindCourse(Request $request)
    {
        // 从请求体验证参数
        $request->validate([
            'student_id' => 'required|integer|exists:students,id',
            'course_id' => 'required|integer|exists:courses,id',
            'start_time' => 'nullable|date'
        ]);

        $student = Student::findOrFail($request->input('student_id'));
        $course = Course::findOrFail($request->input('course_id'));

        // 验证课程归属
        if ($course->teacher_id != auth('admin')->id()) {
            return $this->error('无权操作此课程', 403);
        }

        // 绑定课程（避免重复）
        $student->courses()->syncWithoutDetaching([
            $course->id => [
                'start_time' => $request->input('start_time') ?? now(),
                'progress' => 1
            ]
        ]);

        return $this->success(null, '课程绑定成功');
    }

    /**
     * 取消绑定课程（student_id和course_id放Body）
     * DELETE /api/teacher/students/unbind-course
     */
    public function unbindCourse(Request $request)
    {
        // 从请求体验证参数
        $request->validate([
            'student_id' => 'required|integer|exists:students,id',
            'course_id' => 'required|integer|exists:courses,id'
        ]);

        $student = Student::findOrFail($request->input('student_id'));
        $course = Course::findOrFail($request->input('course_id'));

        // 验证课程归属
        if ($course->teacher_id != auth('admin')->id()) {
            return $this->error('无权操作此课程', 403);
        }

        // 解除绑定
        $student->courses()->detach($course->id);
        return $this->success(null, '课程解绑成功');
    }
}